//
//  CardToolViewController.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/9/5.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit
import SDWebImage

class CardToolViewController: KMViewController {

    fileprivate let cardToolId = "cardToolId"
    fileprivate let selectedId = "selectedId"
    
    fileprivate var tableView : UITableView!
    
    fileprivate var indexPath = 0 //当前cell
    
    fileprivate var titleArray = [shoppingUse,"",cardType,"",selectHobby,"",findRightCardForYou]
    fileprivate var dataArray = [[String]]()
    
    fileprivate var htmlArray = [[String]]() //网页数据
    
    //参数数组
    var keyArray = [String]()
    
    init(title:String?) {
        super.init(nibName: nil, bundle: nil)
        
        self.title = title
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        createTableView()

    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        if tableView != nil {
            
            self.indexPath = 0
            keyArray.removeAll()
            dataArray.removeAll()
            if htmlArray.count > 0 {
                dataArray.append(htmlArray.first!)
            }
            tableView.reloadData()
        }
        
        
    }
    
    //MARK: 解析网页
    fileprivate func getData() {
        
//        KMTool.waiting()
        KMTool.requestGetData(URLString: webUrl + "/mobile/shenqi", parameters: nil, progress: nil, success: { (data) in
            
            self.indexPath = 0
            self.htmlArray.removeAll()
            self.dataArray.removeAll()
            self.tableView.mj_header.endRefreshing()
            
//            KMTool.stop()
            
            let elements = ["//div[@class='applycontent clearfix']/div[@class='custom']/section[@id='s1']/input","//div[@class='applycontent clearfix']/section[@id='s2']/input","//div[@class='applycontent clearfix']/section[@id='s3']/input"]
            let attributes = ["value","value","value"]
            let array = KMTool.htmlToArray(data: data, elements: elements, attributes: attributes)
            
            self.htmlArray = array
            
            self.dataArray = [self.htmlArray[0]]
            self.tableView.reloadData()
        }) {
//           KMTool.stop()
            self.tableView.mj_header.endRefreshing()
        }
                
        
    }
    
    //MARK: 添加tableView
    fileprivate func createTableView() {
        
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CardToolCell.self, forCellReuseIdentifier: cardToolId)
        tableView.register(SelectedTypeCell.self, forCellReuseIdentifier: selectedId)
        self.view.addSubview(tableView)
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        
        KMTool.setRefresh(with: self.tableView, headerAction: {[weak self] in
            
            self?.getData()
            
            }, footerAction: nil)
        
        self.tableView.mj_header.beginRefreshing()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }


}

extension CardToolViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let numbers = self.tableView.numberOfSections
        if numbers > 0 {
            let number = self.tableView.numberOfRows(inSection: numbers-1)
            if number > 1 {
                let ip = NSIndexPath.init(row: number-1, section: numbers-1)
                self.tableView.scrollToRow(at: ip as IndexPath, at: .bottom, animated: true)
            }else{
                let ip = NSIndexPath.init(row: 0, section: 0)
                self.tableView.scrollToRow(at: ip as IndexPath, at: .bottom, animated: true)
            }
        }
        
        if indexPath.row % 2 == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: cardToolId, for: indexPath) as? CardToolCell
            
            cell?.selectionStyle = .none
            cell?.toolDelegate = self
            cell?.titleLabel.text = titleArray[indexPath.row]
            
            if indexPath.row == 6 {
                
                for view in (cell?.collectionView.subviews)! {
                    view.removeFromSuperview()
                }
                
                let path = Bundle.main.path(forResource: "wait", ofType: "gif")
                let data = NSData.init(contentsOfFile: path!)
                let image = UIImage.sd_animatedGIF(with: data! as Data)
                
                //加载gif图片
                let gifView = UIImageView()
                gifView.image = image
                cell?.collectionView.addSubview(gifView)
                
                gifView.snp.makeConstraints { (make) in
                make.top.equalTo((cell?.titleLabel.snp.bottom)!).offset(RATIO_H(maxNum: 10))
                make.left.equalTo((cell?.titleLabel.snp.left)!).offset(RATIO(maxNum: 10))
                    make.width.equalTo(RATIO_H(maxNum: 150))
                    make.height.equalTo(RATIO_H(maxNum: 60))
                }
            }else{
                
                cell?.dataArray = dataArray[indexPath.row]
                cell?.collectionView.isUserInteractionEnabled = indexPath.row == self.indexPath
            }
            return cell!
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: selectedId, for: indexPath) as? SelectedTypeCell
            
            cell?.selectionStyle = .none
            cell?.titleLabel.text = dataArray[indexPath.row].first
            return cell!
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row % 2 == 0 {
            
            if indexPath.row == 6 {
                return RATIO_H(maxNum: 120)
            }else{
                //根据数组元素计算cell高度
                let count = dataArray[indexPath.row].count/2
                let count2 = Float(dataArray[indexPath.row].count)/2.0
                
                let sum = count2 > Float(count) ? count + 1 : count
                let height = RATIO_H(maxNum: 40) * CGFloat(sum) + RATIO_H(maxNum: 50)
                
                return height
            }
        }else{
            return RATIO_H(maxNum: 50)
        }
    }

    
}

extension CardToolViewController : CardToolCellDelegate {
    
    
    //MARK: 选择消费类型
    func selectType(title: String) {
        
        if self.indexPath > 6 {
            return
        }
        
        self.indexPath += 2
        let array = [title]
        self.dataArray.append(array)
        
        switch self.indexPath {
        case 2:
            self.dataArray.append(self.htmlArray[1])
        case 4:
        self.dataArray.append(self.htmlArray[2])
            self.keyArray.append(title)
        case 6:
            self.dataArray.append([String]())
            self.keyArray.append(title)
            
            let time : TimeInterval = 5.0
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
               self.navigationController?.pushViewController(CardDetailsViewController.init(keyArray: self.keyArray,title:self.title!), animated: true)
            }
            
            
        default:
            break
        }
        
        
        self.tableView.reloadData()
    
        
    }
    
    
    
    
}



